import { goodsDetail, apiAddCart, apiGetPayOrder, cartList, apiGetPriceImage, getUpdateLevelByUid, apiGetArticle, apiGetMessageNotice } from '../../api/index'
import { strDiscode } from '../../common/js/parse'

let goodsId
let selectOptions = {} // 用户选择的项  包括颜色、尺码、选中颜色对应的图片地址、选中颜色对应的图片id
let timer
let page = {
  /**
   * 页面的初始数据
   */
  data: {
    commend: true,
    sourceid: 0,
    currentSwiper: 1,
    goodsDetails: {},
    goodsDetail: {},
    show: false,
    intNum: 1,
    changeSelect: 0,
    detailBanner: [],
    showType: 0, // 显示规格弹窗由谁调起，0是直接点规格，1是点击加入购物车，2是立即购买
    goodStatus: true, // true 为有货，false 为无货
    skuColorList: {}, // 所有颜色下面的有库存的尺码（用来置灰没有库存的尺码）
    skuSizeList: {}, // 所有尺码下面的有库存的颜色（用来置灰没有库存的颜色）
    specList: [], // 所有的颜色尺码等spec分类
    goodsName: '',
    skuId: '',
    skuName: '',
    colorSelected: '',
    sizeSelected: '',
    curPic: '',
    picture: null,
    minPrice: '',
    maxPrice: '',
    price: '',
    showPrice: 0,
    costPrice: '',
    goodsSku: '',
    stock: 0,
    makeMoney: '',
    makeSingleMoney: '',
    makesMoney: '',
    shareMoney: '',
    shareImageUrl: '',
    serve: 0,
    isShowMoney: false,
    target: false,
    goodsType: '',
    showSelectMoney: false,
    loads: true,
    index: 0,
    showData: [],
    showTip: ''
  },
  // 关闭赚说明
  closeZhuan () {
    this.setData({
      isShowMoney: false
    })
  },
  // 是否展开说明
  targetExpress () {
    this.setData({
      target: !this.data.target
    })
    if (this.data.target) {
      wx.pageScrollTo({
        scrollTop: this.data.scrollTop + 530
      })
    }
  },
  onPageScroll (e) {
    this.data.scrollTop = e.scrollTop
  },
  // 轮播图计数器
  changeSwiper (e) {
    this.setData({
      currentSwiper: e.detail.current + 1
    })
  },
  // 选择规格
  selectSpe () {
    // this.setData({ show: true, serve: 0, showSelectMoney: false })
    this.setData({ show: true, serve: 0 })
  },
  onClose () {
    this.setData({ show: false })
  },
  // 确定按钮
  isSure () {
    if ((this.data.goodsDetails.spec_list.length === 1 && !this.data.colorSelected) || (this.data.goodsDetails.spec_list.length === 2 && (!this.data.sizeSelected || !this.data.colorSelected))) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
        mask: true
      })
      return
    }
    if (!this.data.goodStatus) {
      wx.showToast({
        title: '所选商品无货',
        icon: 'none',
        mask: true
      })
      return
    }
    if (this.data.showType === 1) {
      // 加入购物车
      this.addCar()
    } else if (this.data.showType === 2) {
      this.toPay()
    }
    this.setData({
      show: false,
      makesMoney: this.makesMoney,
      showSelectMoney: true
    })
  },
  bindKeyInput (e) {
    this.setData({
      intNum: e.detail.value.replace(/[^\d]/g, '')
    })
  },
  // 输入购买数量
  intNum (e) {
    var value = e.detail.value.replace(/[^\d]/g, '')
    setTimeout(() => {
      this.setData({
        intNum: value
      })
    }, 0)
  },
  // 加
  add () {
    this.max_buy = this.data.goodsDetails.max_buy > 0 ? this.data.goodsDetails.max_buy : this.data.stock
    let num = this.data.intNum - 0 + 1
    if (num > this.max_buy) {
      wx.showToast({
        title: '超出库存了',
        icon: 'none'
      })
    } else {
      this.makesMoney = Math.floor((this.data.goodsDetails.make_money - 0) * num * 100) / 100
      this.setData({
        intNum: num
      })
    }
  },
  // 减
  reduce () {
    console.log(this.data.intNum)
    let num = this.data.intNum - 1

    this.min_buy = this.min_buy > 0 ? this.min_buy : 1
    if (num < this.min_buy) {
      wx.showToast({
        title: '不能再少啦~',
        icon: 'none'
      })
    } else {
      // num = num > 1 ? num : 1
      this.makesMoney = Math.floor((this.data.goodsDetails.make_money - 0) * num * 100) / 100
      this.setData({
        intNum: num
      })
    }
  },
  // 选择sku
  chengeSelect (e) {
    this.data.goodsSku = e.target.dataset.item
    let data = e.target.dataset.item // 点击项目的信息
    let goodsDetails = this.data.goodsDetails
    // 1、点击 边框变红 和 切换图片
    let specShowType = Number(data.spec_show_type)
    if (specShowType === 1) {
      selectOptions.colorSelected = data.spec_value_name === this.data.colorSelected ? '' : data.spec_value_name
      // 切换图片
      var skuPicture = goodsDetails.sku_picture_list.find(item => {
        return item.spec_value_name === data.spec_value_name
      })
      if (skuPicture) {
        selectOptions.curPic = skuPicture.sku_picture_query[0] && skuPicture.sku_picture_query[0].pic_cover_mid
        selectOptions.picture = skuPicture.sku_img_array
      }
    } else if (specShowType) {
      selectOptions.sizeSelected = data.spec_value_name === this.data.sizeSelected ? '' : data.spec_value_name
    }
    // 2、显示价格 和 有无货
    let color = selectOptions.colorSelected
    let size = selectOptions.sizeSelected
    // 两个商品规格
    if (goodsDetails.spec_list.length === 2) {
      if (color && size) {
        // 勾选两个
        let selItem = this.data.skuColorList[color][size]
        if (selItem) {
          // 有对应的sku
          this.makesMoney = Math.floor(selItem.make_money * this.data.intNum * 100) / 100
          selectOptions.price = selItem.price
          selectOptions.costPrice = selItem.cost_price
          selectOptions.goodStatus = selItem.stock > 0
          selectOptions.skuId = selItem.sku_id
          selectOptions.skuName = selItem.sku_name
        } else {
          // 没有对应的sku
          selectOptions.price = this.data.minPrice !== '' ? 0 : this.data.price
          selectOptions.costPrice = ''
          selectOptions.goodStatus = false
          selectOptions.skuId = ''
          selectOptions.skuName = ''
        }
      } else {
        // 只勾选一个
        selectOptions.price = this.data.minPrice ? 0 : this.data.price
        selectOptions.costPrice = ''
        selectOptions.goodStatus = true
        selectOptions.skuId = ''
        selectOptions.skuName = ''
      }
    } else if (this.data.goodsDetails.spec_list.length === 1) {
      // 一个商品规格
      if (color) {
        let selItem = this.data.skuColorList[color]
        if (selItem) {
          // selectOptions.makesMoney = selItem.make_money
          this.makesMoney = Math.floor(selItem.make_money * this.data.intNum * 100) / 100
          selectOptions.price = selItem.price
          selectOptions.costPrice = selItem.cost_price
          selectOptions.goodStatus = selItem.stock > 0
          selectOptions.stock = selItem.stock
          selectOptions.skuId = selItem.sku_id
          selectOptions.skuName = selItem.sku_name
        } else {
          selectOptions.price = this.data.minPrice ? 0 : this.data.price
          selectOptions.costPrice = ''
          selectOptions.goodStatus = false
          selectOptions.stock = 0
          selectOptions.skuId = ''
          selectOptions.skuName = ''
        }
      } else {
        selectOptions.price = this.data.minPrice ? 0 : this.data.price
        selectOptions.costPrice = ''
        selectOptions.goodStatus = true
        selectOptions.skuId = ''
        selectOptions.skuName = ''
      }
    }
    selectOptions.showPrice = Math.round((selectOptions.price - 0) * 100) / 100
    this.setData(selectOptions)
  },
  // 立即购买
  clickPop () {
    let data = this.data
    if (this.data.goodsDetails.sku_list[0].sku_name !== '') {
      if (!data.skuName) {
        this.setData({
          showType: 2,
          serve: 0
        })
        this.selectSpe()
        return
      }
    }
    this.toPay()
  },
  toPay () {
    apiGetPayOrder({
      order_tag: 'buy_now',
      order_sku_list: this.data.skuId ? this.data.skuId + ':' + this.data.intNum : this.data.goodsDetails.sku_list[0].sku_id + ':' + this.data.intNum
    }).then(
      res => {
        let data = JSON.stringify(res.data.itemlist)
        let shipping = JSON.stringify(res.data.express_company_list)
        // 立即购买
        wx.navigateTo({
          url: `../shop-detail-order/shop-detail-order?data=${data}&shipping=${shipping}`
        })
      })
  },
  // 获取购物车列表
  getCarList () {
    cartList().then(
      res => {
        this.setData({
          tag: res.data.cart_list.length
        })
      }
    )
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    if (options.help) {
      this.helpSum = JSON.parse(options.help)
    }
    let scene = decodeURIComponent(options.scene)
    let sourceid = options.source_uid
    let goodsType
    if (options.goods_type && options.goods_type === '1') {
      goodsType = options.goods_type
    }
    // 判断机型
    this.setData({
      isIphoneX: getApp().globalData.isIphoneX,
      navHeight: getApp().globalData.navHeight * 2,
      iPad: getApp().globalData.iPad,
      goodsType: goodsType || ''
    })
    goodsId = options.id
    if (options.source_uid) {
      this.source_uids = options.source_uid
      this.setData({
        sourceid: Number(sourceid)
      })
    }
    this.init()
    if (scene && scene !== 'undefined') {
      let souceArr = scene.match(/source_uid=(\d*)/)
      if (souceArr.length > 1) {
        sourceid = souceArr[1]
      }
    }
    this.getCarList()
    this.getData()
    timer = setInterval(
      () => {
        this.animations()
      }, 6000)
  },
  // 悬浮窗获取提示数据
  getData () {
    // 详情图片
    apiGetArticle({ article_id: 2 }).then(
      res => {
        res.data.content = res.data.content.replace(/\<img/gi, '<img class="rich-img" ')
        this.setData({
          bottomImg: res.data.content
        })
      }
    )
    apiGetMessageNotice().then(
      res => {
        this.setData({
          showData: res.data
        })
      }
    )
  },
  animations () {
    this.data.index++
    if (this.data.index === this.data.showData.length) {
      this.data.index = 0
    }
    this.setData({
      showTip: this.data.showData[this.data.index]
    })
    setTimeout(() => {
      this.setData({
        showTip: ''
      })
    }, 4000)
  },
  init () {
    goodsDetail({ goods_id: goodsId, source_uid: this.source_uids }).then((res) => {
      res.data.price = (Math.round(res.data.price * 100) / 100).toString()
      this.data.stock = res.data.stock
      /* eslint-disable */
      res.data.description = res.data.description.replace(/\<img/gi, '<img class="rich-img" ')
      res.data.description = strDiscode(res.data.description)
      /* eslint-enable */
      let skuList = res.data.sku_list
      let colorList = {}
      let sizeList = {}
      let min
      let max
      let price
      // sku 整理归类，并求价格区间
      skuList.forEach(item => {
        let skuListArr = item.sku_name.split(' ')
        let color = skuListArr[0]
        let size = skuListArr[1]
        // 两个商品规格
        if (item.stock > 0 && res.data.spec_list.length > 1) {
          if (!colorList[color]) {
            colorList[color] = {}
          }
          if (!sizeList[size]) {
            sizeList[size] = {}
          }
          colorList[color][size] = item
          sizeList[size][color] = item
        }
        // 一个商品规格
        if (item.stock > 0 && res.data.spec_list.length === 1) {
          colorList[color] = item
        }
        // 求商品价格区间
        if (!min || Number(this.data.minPrice) > Number(item.price)) {
          min = item.price
        }
        if (!max || Number(this.data.maxPrice) < Number(item.price)) {
          max = item.price
        }
      })
      if (min === max) {
        price = max
        min = max = ''
      }
      // 重置spec 里面规格的 spec_show_type 按次序
      let specList = res.data.spec_list
      specList.forEach((spec, index) => {
        spec.value.map(item => {
          item.spec_show_type = index + 1
          return item
        })
      })
      let pictureList = res.data.sku_picture_list
      this.pic_list = pictureList.length > 0 && pictureList[0].sku_picture_query.length > 0 && pictureList[0].sku_picture_query[0].pic_cover_mid
      this.setData({
        nickName: JSON.stringify({ nickName: wx.getStorageSync('nickName'), city: wx.getStorageSync('city') }),
        goodsDetails: res.data,
        makeSingleMoney: res.data.make_money.toFixed(2),
        shareMoney: res.data.share_money.toFixed(2),
        specList,
        skuColorList: colorList,
        skuSizeList: sizeList,
        goodsName: res.data.goods_name,
        maxPrice: max,
        minPrice: min,
        price: price || 0,
        stock: res.data.stock,
        curPic: this.pic_list || res.data.img_list[0].pic_cover_mid,
        picture: pictureList.length > 0 && pictureList[0].sku_img_array || res.data.img_list[0].pic_id,
        loads: false
      })
    })
  },
  // 加入购物车
  addCar () {
    let data = this.data
    let skuName, skuId
    if (this.data.goodsDetails.sku_list[0].sku_name === '') {
      skuName = ''
      skuId = this.data.goodsDetails.sku_list[0].sku_id
    } else {
      if (!data.skuName) {
        this.setData({
          showType: 1,
          serve: 0
        })
        this.selectSpe()
        return
      }
    }
    const params = {
      shop_name: '多拿点',
      goods_id: this.data.goodsDetails.goods_id,
      goods_name: this.data.goodsDetails.goods_name,
      num: data.intNum - 0,
      select_skuid: data.skuId - 0 || skuId,
      select_skuName: data.skuName || skuName,
      price: this.data.goodsDetails.price,
      cost_price: this.data.goodsDetails.cost_price,
      picture: data.picture - 0,
      loading: 1
    }
    apiAddCart(params).then(
      res => {
        wx.showToast({
          title: '已加入购物车'
        })
        this.getCarList()
      }
    )
  },
  // 跳转到首页
  goHome () {
    wx.switchTab({
      url: '../shopping/shopping'
    })
  },
  goShopCar () {
    wx.switchTab({
      url: '../shop-car/shop-car'
    })
  },
  // 会员中心
  toCenter () {
    wx.navigateTo({
      url: '../distribution-center/distribution-center'
    })
  },
  // 调起服务
  serves () {
    this.setData({
      show: true,
      serve: 1
    })
  },
  serveClose () {
    this.setData({
      show: false,
      serve: 1
    })
  },
  // 监测是否授权
  changeAuthStatus (e) {
    this.setData({
      commend: e.detail.status
    })
    getUpdateLevelByUid({ source_uid: this.source_uids, loading: 1 }).then(
      res => {}
    )
  },
  // 分享
  shareMsg () {
    console.log(goodsId)
    apiGetPriceImage({
      goods_id: goodsId
    }).then(res => {
      console.log(res)
      this.setData({
        shareImageUrl: res.data,
        show: true,
        serve: 2
      })
    })
  },
  creatImgs () {
    let goods = {}
    goods['goods_name'] = this.data.goodsDetails.goods_name
    goods['picture_info'] = this.data.goodsDetails.picture_detail
    goods['make_money'] = this.data.goodsDetails.make_money
    goods['price'] = this.data.goodsDetails.price
    goods['goods_id'] = this.data.goodsDetails.goods_id
    wx.navigateTo({
      url: `../create-img/create-img?data=${JSON.stringify(goods)}`
    })
  },
  // 关闭分享
  cancelPop () {
    this.setData({
      show: false,
      serve: 2
    })
  },
  // 赚说明
  makePrice () {
    this.setData({
      isShowMoney: true
    })
  },
  onHide () {
    clearInterval(timer)
    this.setData({
      show: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    this.setData({
      show: false
    })
    let data
    if (this.data.goodsType) {
      data = {
        id: this.helpSum.id,
        number: this.helpSum.number,
        goods_id: goodsId - 0
      }
    }
    let title = this.data.goodsType ? '助力好友，即可拿佣金' : wx.getStorageSync('nickName') + '分享给你，数量有限，先到先得！'
    return {
      title,
      imageUrl: this.data.shareImageUrl,
      path: this.data.goodsType ? `/pages/assistance-detail/assistance-detail?data=${JSON.stringify(data)}&source_uid=${this.helpSum.uid}` : `/pages/goods-detail/goods-detail?id=${goodsId}&source_uid=${wx.getStorageSync('uid')}`
    }
  }
}
Page(page)
